package us.gaaoc.framework.webapp.backingbeans.attorney;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.security.cert.CertPath;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.validator.ValidatorException;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.transaction.annotation.Transactional;

import us.gaaoc.framework.dao.PersonParticipantsDAOHibernate;
import us.gaaoc.framework.model.Attorney;
import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.CaseRecordHistory;
import us.gaaoc.framework.model.CaseRecordIdExternalCaseRecordNumber;
import us.gaaoc.framework.model.CaseRecordStatus;
import us.gaaoc.framework.model.Counter;
import us.gaaoc.framework.model.CounterPerSigner;
import us.gaaoc.framework.model.Court;
import us.gaaoc.framework.model.CourtEvents;
import us.gaaoc.framework.model.DocumentStatus;
import us.gaaoc.framework.model.Documents;
import us.gaaoc.framework.model.LdapDirectoryPerson;
import us.gaaoc.framework.model.OrgParticipants;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.model.PersonParticipants;
import us.gaaoc.framework.model.Signatures;
import us.gaaoc.framework.model.constants.Constants;
import us.gaaoc.framework.signature.digital.DigitalSigner;
import us.gaaoc.framework.signature.digital.DigitalSignerController;
import us.gaaoc.framework.signature.digital.SignatureAndCertChain;
import us.gaaoc.framework.signature.digital.SignatureValidator;
import us.gaaoc.framework.signature.digital.ldap.LdapClient;
import us.gaaoc.framework.signature.visual.PDFStamper;
import us.gaaoc.framework.signature.visual.PDFStamperController;
import us.gaaoc.framework.util.DateUtil;
import us.gaaoc.framework.util.LocalCaseInformation;
import us.gaaoc.framework.util.io.FileUtility;
import us.gaaoc.framework.webapp.backingbeans.BaseBackingBean;
import us.gaaoc.framework.webapp.backingbeans.attorney.actions.SendToCourtAction;
import us.gaaoc.framework.webapp.util.Messages;

import com.lowagie.text.Image;

/**
 * 
 * @author hea
 * @date Apr 19, 2006
 * @version: GAJE 1.5
 * 
 */
@SuppressWarnings( {"unchecked", "unused"} )

public class CaseDetailsPage extends BaseBackingBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8285564163255455863L;

	/**
	 * Properties
	 */
	private CaseRecord caseRecord;

	private String caseRecordUuid;

	private String filerName;

	private String OCSSCaseNumber;
	
	private String courtCaseNumber;
	
	private boolean renderSignedText;

	/**
	 * Data Models for the personParticipants
	 */
	private DataModel initiatingPartyPersonModel;

	private DataModel defendentPartyPersonModel;

	private DataModel witnessPersonModel;

	private DataModel plantiffsAttorneyModel;

	private DataModel defendentsAttorneyModel;

	private DataModel initiatingPartyOrganizationDataModel;

	private boolean renderSetCourtDate;
	
	//private DataModel documentsModel;
	/*
	 * List of Imported Documents
	 */
	private List<Documents> importedDocumentsList;
	private DataModel importedDocumentsModel;
	
	/*
	 * List of Uploaded Documents
	 */
	private List<Documents> uploadedDocumentsList;
	private DataModel uploadedDocumentsModel;

	private Date courtDate, proposedCourtDate;

	private static transient Logger LOG = Logger
			.getLogger(CaseDetailsPage.class);

	private String caseCaption;

	private List<Documents> documentList;

	private String organizationName = null;

	private UIParameter signatureBinding;
	
	private UIParameter documentClicked_Uploaded;
	
	private UIParameter documentClicked_Imported;

	private DataModel signaturesListModel;

	private List<Signatures> signaturesList;

	private DataModel sigantureCounterPerSignerModel;

	private CounterPerSigner signatureCounterPerSigner;

	private DataModel signatureCounterModel;

	private Counter signatureCounter;

	// private Documents signedDoc;

	private Documents docSignedByThisPerson;

	private String signatureConfTrackNumber;

	private boolean renderModifyButton;

	private boolean renderSubmitButton;

	private boolean renderSignButton;
	
	private boolean renderRejectReasonButton;

	private String signatureTrackingID;

	private FacesMessage message;
	
	private String jurisdiction;
	
	private DigitalSignerController digitalSignerController = new DigitalSignerController();

	private PDFStamperController pdfStamperController= new PDFStamperController();
	
	private boolean renderFileNewDocuments;
	
	private String courtUuid;
	
	SendToCourtAction sendToCourtAction = new SendToCourtAction();

	private boolean validCase;
	
	private UIInput commentsInput;
	
	//private boolean renderUpdateCourtCaseNumber;

	public boolean isRenderSetCourtDate() {
		return renderSetCourtDate;
	}
	
	public void setRenderSetCourtDate(boolean renderSetCourtDate) {
		this.renderSetCourtDate = renderSetCourtDate;
	}
    
    /**
	 * @return the commentsInput
	 */
	public UIInput getCommentsInput() {
		return commentsInput;
	}

	/**
	 * @param commentsInput the commentsInput to set
	 */
	public void setCommentsInput(UIInput commentsInput) {
		this.commentsInput = commentsInput;
	}

	/**
	 * @return the comments
	 */
	public String getComments() {
		return comments;
	}

	/**
	 * @param comments the comments to set
	 */
	public void setComments(String comments) {
		this.comments = comments;
	}

	private String comments;
	
	/**
	 * Constructor
	 * 
	 */
	public CaseDetailsPage() {
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String caseUuid = (String) sessionMap.get("caseUuid");
		if(caseUuid!=null)
		this.loadData();
	}

	/**
	 * This method loads data from the database
	 * 
	 */
	private void loadData() {

		validCase = true;
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		courtUuid = (String)sessionMap.get("courtUuid");
		try {
			this.setJurisdiction(LocalCaseInformation.getJurisdiction(courtUuid));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Court court = this.getModelFacade().findCourt(courtUuid);
		
		
		{//court rendering logic.
			if(court.getUuid().equalsIgnoreCase("courtUuidCrawford"))
			{
				this.setRenderSetCourtDate(false);
			}else{
				this.setRenderSetCourtDate(true);
			}
		}
		
		
		String caseUuid = (String) sessionMap.get("caseUuid");
		String fromPage = (String) sessionMap.get("from");

		CaseRecord c = (CaseRecord) this.getModelFacade().findCaseRecordById(
				caseUuid, courtUuid);
		this.setCaseRecordUuid(caseUuid);
		this.setCaseRecord(c);
		Person personSigned = (Person) sessionMap.get("person");

		/*
		Hibernate.initialize(c.getPersonParticipants());
		Hibernate.initialize(c.getOrgParticipants());
		Hibernate.initialize(c.getDocuments());
		Hibernate.initialize(c.getStatus());
		Hibernate.initialize(c.getLocalCaseCategory());
		Hibernate.initialize(c.getLocalCaseDivision());
		Hibernate.initialize(c.getLocalCaseFilingType());
		Hibernate.initialize(c.getLocalCaseType());
		
		for (int i=0; i< c.getPersonParticipants().size(); i++) {
			Hibernate.initialize(c.getPersonParticipants().get(i).getPerson().getAddresses());
		}
		for (int i=0; i< c.getOrgParticipants().size(); i++) {
			Hibernate.initialize(c.getOrgParticipants().get(i).getOrganizations().getAddresses());
		}
		for (int i = 0; i < c.getDocuments().size(); i++) {
			Hibernate.initialize(c.getDocuments().get(i).getDocumentInstance());
		}
	

		if (courtUuid.equalsIgnoreCase("courtUuidCoweta")) {
			this.setRenderUpdateCourtCaseNumber(true);
		}
		
		*/
		List<PersonParticipants> pParticipantsList = c.getPersonParticipants();
		List<OrgParticipants> oParticipantsList = c.getOrgParticipants();
		//String caseStatus = c.getStatus().getDescription();
		int caseStatusCode = c.getStatus().getCode();

		//if (caseStatus.equals("ReadyToSendToCourt")) {
		//caseStatus = "ReadyToSendToCourt" for statusCode = 11
		if (caseStatusCode == 11) {
			this.setRenderSubmitButton(true);

		} else {
			this.setRenderSubmitButton(false);
		}

		/*
		 * changed from status description to status code
		if (caseStatus.equals("SentToAttorney")
				|| (caseStatus.equals("Rejected")) || (caseStatus.equals("UnsentAddition")))
			this.setRenderModifyButton(true);
		 */
		// else
		//this.setRenderModifyButton(false);
		
		//caseStatus = "SentToAttorney" for statusCode = 10
		//caseStatus = "Rejected" for statusCode = 3
		//caseStatus = "SentToAttorneyAddition" for statusCode = 16
		//caseStatus = "RejectedByJudge" for statusCode = 19
		//caseStatus = "ReadyToSendToCourt" for statusCode = 11
		//caseStatus = "Imported" for statusCode = 2
		
		if (caseStatusCode == 10	
				|| (caseStatusCode == 16) 
				|| (caseStatusCode == 3) 
				|| (caseStatusCode == 19)
				|| (caseStatusCode == 11)){
			this.setRenderModifyButton(true);
		}
		
		//System.out.println("****************CASE STATUS CODE = " + caseStatusCode);
			
		/*
		 * Edited by Brandon Denney
		 * 2008/06/24
		 * 
		 * If the case status is any of the following codes,
		 * the reject button should be rendered:
		 * 
		 *  3 - Rejected
		 * 10 - SentToAttorney
		 * 11 - ReadyToSendToCourt
		 * 16 - SentToAttorneyAddition
		 * 19 - RejectedByJudge
		 */		
		if (caseStatusCode == 3 
			|| caseStatusCode == 19 
			|| caseStatusCode == 10
			|| caseStatusCode == 11
			|| caseStatusCode == 16) {
			this.setRenderRejectReasonButton(true);
		}

		List initiatingPartyOrganizationList = new ArrayList();

		// for initiating party person list
		List initiatingPartyPersonList = new ArrayList();

		// for defendent party person list
		List defendentPartyPersonList = new ArrayList();

		// for witness person list
		List witnessPersonList = new ArrayList();

		// for plantiff's Attorneys
		List plantiffsAttorneyList = new ArrayList();

		// for defendent's Attorneys
		List defendentsAttorneyList = new ArrayList();

		String initiatingPartyOrg = "";
		
		for (OrgParticipants o : oParticipantsList) {
			if (o.getRelationship().getCode() == 1)
			{
				initiatingPartyOrganizationList.add(o);
				initiatingPartyOrg = o.getUuid();
			}
		}
		this.setFilerName("");
		PersonParticipants kcr = null;
		for (PersonParticipants o : pParticipantsList) {
			if (o.getRelationship().getCode() == 1)
				initiatingPartyPersonList.add(o);
			else if (o.getRelationship().getCode() == 2)
				defendentPartyPersonList.add(o);
			else if (o.getRelationship().getCode() == 3)
				witnessPersonList.add(o);
			else if (o.getRelationship().getCode() == 4 && !o.getPerson().getFirstName().equalsIgnoreCase("ff20da2c-8e5c-11dd-9b78-0016d3"))
			{
				String barID = this.getModelFacade().getBarID(o.getPerson(), court);
				if (barID.equals("597910")) { 
					kcr = o;
				}
				Attorney a = new Attorney();
				LOG.debug("1");
				a.setBarID(barID);
				LOG.debug("2");
				a.setPerson(o.getPerson());
				LOG.debug("3");
				o.getPerson().setAttorney(a);
				LOG.debug("4");
				plantiffsAttorneyList.add(o);
				LOG.debug("5");
			}
			else if (o.getRelationship().getCode() == 5)
				defendentsAttorneyList.add(o);
			else if (o.getRelationship().getCode() == 6) {
				Person filer = o.getPerson();
				this.setFilerName(
						this.getFilerName() + " , " + 						
						filer.getFirstName() + " "
						+ filer.getMiddleName() + " " + filer.getLastName());
			}
		}
		
		this.setFilerName(this.getFilerName().replaceFirst(",",""));
		
		
		
		//The following block is for Fulton's SAAG office Kathryn C. Reeder
		if(courtUuid.equals("courtUuid4")){
			Person person = this.getModelFacade().findAttorneyByBarIDAndOrgAsPerson("597910", "initiatingPartyOrganizationUuid4");
			if(person != null)
			{
				List<PersonParticipants> ppList = this.getModelFacade().getPersonParticipantByPerson(person);
				if (!ppList.isEmpty() && this.getModelFacade().getPersonParicipant(c).contains(person)){
					plantiffsAttorneyList.clear();
					plantiffsAttorneyList.add(kcr);
				}
			}
		}
		//End
		
/*		//set OCSS case number
		String externalCaseNumber = this.getModelFacade().findExternalCaseRecordNumbers(c.getUuid()).get(0).getExternalCaseRecordNumber();
		this.setOCSSCaseNumber(externalCaseNumber);*/
		
		//set OCSS case number
		List<CaseRecordIdExternalCaseRecordNumber> externalCaseIds = 
		    this.getModelFacade().findExternalCaseRecordNumbers(caseUuid);
		if (!externalCaseIds.isEmpty()) {
		    // TODO Need to have types to classify the external 
		    // identifiers
		    CaseRecordIdExternalCaseRecordNumber externalCaseId = externalCaseIds.get(0);
		    String externalCaseNumber = externalCaseId.getExternalCaseRecordNumber();
		    this.setOCSSCaseNumber(externalCaseNumber);
		}
		
				
		//set court case number(docketID)
		String docketID = c.getCaseTrackingId();
		this.setCourtCaseNumber(docketID);

		initiatingPartyOrganizationDataModel = new ListDataModel();
		initiatingPartyOrganizationDataModel
				.setWrappedData(initiatingPartyOrganizationList);

		initiatingPartyPersonModel = new ListDataModel();
		initiatingPartyPersonModel.setWrappedData(initiatingPartyPersonList);

		defendentPartyPersonModel = new ListDataModel();
		defendentPartyPersonModel.setWrappedData(defendentPartyPersonList);

		witnessPersonModel = new ListDataModel();
		witnessPersonModel.setWrappedData(witnessPersonList);

		defendentsAttorneyModel = new ListDataModel();
		defendentsAttorneyModel.setWrappedData(defendentsAttorneyList);

		plantiffsAttorneyModel = new ListDataModel();
		plantiffsAttorneyModel.setWrappedData(plantiffsAttorneyList);

		List<Documents> pdfList = new ArrayList<Documents>();
		//List<Documents> xmlList = new ArrayList<Documents>();
		//List<Documents> xslList = new ArrayList<Documents>();

		List<Documents>iDocs = new ArrayList<Documents>();
		List<Documents>eDocs = new ArrayList<Documents>();
		
		boolean docOrder = false;
		boolean docSigned = false;

		pdfList = this.getModelFacade().getPDFDocuments(caseUuid);
		boolean orderFlag = false;
		boolean allowSendToClerk = true;
		LOG.debug("1- pdfList.size() is "+pdfList.size());
		if (pdfList.size() != 0) {
			
			List<PersonParticipants > l = this.getModelFacade().getPersonParticipantByParticipantRelationshipCode
			(c, 4);
			for (Documents doc : pdfList) {
			

				docOrder = digitalSignerController.isDocumentOrderForAttorney(doc);
				docSigned = digitalSignerController.isDocumentSignedForAttorney(doc, personSigned);
				
					for(PersonParticipants pp : l)
					{
						if(pp.getRelationship().getCode() == 4)
						{
							if(	(!pp.getPerson().getUuid().equalsIgnoreCase(personSigned.getUuid())
									&& !pp.getPerson().getFirstName().equalsIgnoreCase("ff20da2c-8e5c-11dd-9b78-0016d3"))
									&& (c.getCaseTrackingId() != null && !c.getCaseTrackingId().equalsIgnoreCase("") && !docOrder)) 
							{
								if(docOrder == true) allowSendToClerk = false;
								docOrder = false;
								docSigned = false;
								
							}
						}
					}
					


					doc.setOrderedDoc(docOrder);
					doc.setSignedDoc(docSigned);
					/*
					if (docOrder) {
						doc.setOrderedDoc(true);
						orderFlag = true;
						if (docSigned) {
							doc.setSignedDoc(true);
							this.renderSignedText = true;
							this.renderSignButton = false;
						} else {
							doc.setSignedDoc(false);
							this.renderSignedText = false;
							this.renderSignButton = true;				
						}			
					}else{
						doc.setOrderedDoc(false);
					}
					
					
					if(! this.getModelFacade().getPersonParticipantByParticipantRelationshipCode
							(c, 4).get(0).getUuid().equalsIgnoreCase(personSigned.getUuid()))
					{
						int documentCategory = doc.getDocumentInstance().getDocumentType().getDocumentCategory().getCode();
						if((documentCategory == 10 || documentCategory == 12))
						{
							
							this.renderSignedText = true;
							this.renderSignButton = false;
							doc.setSignedDoc(docSigned);
							doc.setOrderedDoc(true);
							orderFlag = true;
						}else{
							this.renderSignButton = false;
							this.renderSignedText = false;
							doc.setSignedDoc(false);
							doc.setOrderedDoc(false);
							orderFlag = false;
						}
					}
					
				
			/*else{
					int documentCategory = doc.getDocumentInstance().getDocumentType().getDocumentCategory().getCode();
					if((documentCategory != 10 && documentCategory != 12))
					{
						this.renderSignedText = true;
						this.renderSignButton = false;
					}else{
						docOrder = digitalSignerController.isDocumentOrderForAttorney(doc);
						docSigned = digitalSignerController.isDocumentSignedForAttorney(doc, personSigned);
						if (docOrder) {
							if (docSigned) {
								this.renderSignedText = true;
								this.renderSignButton = false;
							} else {
								this.renderSignedText = false;
								this.renderSignButton = true;
							}
						}
					}
				}
				*/
			}
			//caseStatus = "Received" for statusCode=1;
			//caseStatus = "ReceivedByJudge" for statusCode=13;
			if (!((caseStatusCode == 1) || (caseStatusCode == 13)) ) {
				this.updateDatabaseAfterAllSigned(pdfList, personSigned);

			} else {
				this.setRenderSubmitButton(false);
				this.setRenderModifyButton(false);
			}
			
			boolean additonSummonRuleNisi = false;
			
			for (Documents doc : pdfList) {
				int documentTypeCode = doc.getDocumentInstance().getDocumentType().getCode();
				int docStatusCode = doc.getStatus().getCode();
				/*
				 * Codes:
				 * 
				 * Document Type Code 34 = Judicial Summons
				 * Document Status Code 6 = Uploaded
				 * Case Status Code 16 =  Sent To Attorney Addition
				 */
				 //Added by Frank
				if ( documentTypeCode == 34 
						&& (docStatusCode == 6) 
						&& caseStatusCode == 16) {
					additonSummonRuleNisi = true;
				}
				//End

				//orderFlag = digitalSignerController.isDocumentOrderForAttorney(doc);
				if (!orderFlag) {
					//caseStatus = "ReadyToSendToCourt";
					//statusCode = 11;
					
					//if the document is not an order for attorney, then the 
					// document does not NEED to be signed by the attorney.
					// - Shawn Artrip

				} else {
					//caseStatus = "SentToAttorney";
					//statusCode = 10;
					docSigned = digitalSignerController.isDocumentSignedForAttorney(doc, personSigned);
					if(docSigned)
					{
						this.setRenderSubmitButton(true);
					}else{
						this.setRenderSubmitButton(false);
					}
					break;
				}

			}
			if ((fromPage.equalsIgnoreCase("searchPage") || (fromPage.equalsIgnoreCase("attFilingsTablesPage")) ||
					fromPage.equalsIgnoreCase("allFilingsTablesPage")) && 
					((caseStatusCode == 2) || (caseStatusCode == 1) || (caseStatusCode == 20))) {
				this.setRenderFileNewDocuments(true);
			}

		/*	if (caseStatusCode == 1) {
				this.setRenderModifyButton(true);
			} */
			
			//caseStatus = "SentToAttorneyAddition" for statusCode=16;
			if ( (caseStatusCode == 16) && additonSummonRuleNisi) {
				//this.setRenderSubmitButton(true);
				this.setRenderModifyButton(true);
			}
		
		} else if (caseStatusCode !=2 && caseStatusCode != 20 && caseStatusCode !=1 && caseStatusCode != 16){
			this.setRenderSubmitButton(true);
			this.setRenderModifyButton(true);
		} else {
			this.setRenderModifyButton(true);
		}
		

		/*
		 * docOrder = isDocumentOrder(doc); //docSigned =
		 * isDocumentSigned(doc.getStatus().getCode()); docSigned =
		 * isDocumentSigned(doc,personSigned); if(docOrder) { if(docSigned) {
		 * this.renderSignedText = true; this.renderSignButton = false; } else {
		 * this.renderSignedText = false; this.renderSignButton = true; } }
		 */

		// Frank added the following block
		/*
		 * for(Documents d :xmlList) { LOG.debug("Max Version of the document
		 * :"+d.getDocumentType().getCode()+" is "+d.getVersion()); String
		 * docCode= d.getDocumentType().getCode(); this.renderSignButton =
		 * false; this.renderSignedText = false; docOrder = isDocumentOrder(d);
		 * docSigned = isDocumentSigned(d,personSigned); if(docOrder) {
		 * if(docSigned) { this.renderSignedText = true; this.renderSignButton =
		 * false; } else { this.renderSignedText = false; this.renderSignButton =
		 * true; } } }
		 */
/*
		if (pdfList.size() > 0) {
			this.setDocumentList(pdfList);
		}
*/
		LOG.debug("10");
		pdfList = this.getModelFacade().getPDFDocuments(caseUuid);
		//added by Michael A to get the list of pdf's signed  by the attorney or not, to display 
		
		LOG.debug("2 - pdfList.size() is "+pdfList.size());
		for(Documents document : pdfList) {
			int docStatusCode = document.getStatus().getCode();
			if(docStatusCode == Constants.DocumentStatus.IMPORTED) 
			{
				iDocs.add(document);
			} 
			else 
			{
				eDocs.add(document);
			}
		}
		
		this.setDocumentList(pdfList);
		this.setImportedDocumentsList(iDocs);
		this.setUploadedDocumentsList(eDocs);
		
		boolean ArenderSubmitbutton = true;
		for (Documents doc : pdfList) {
			docOrder = digitalSignerController.isDocumentOrderForAttorney(doc);
			docSigned = digitalSignerController.isDocumentSignedForAttorney(doc, personSigned);
			if (docOrder) {
				if (!docSigned) {
					ArenderSubmitbutton = false;
				}
			}
		}
		if(ArenderSubmitbutton)
		{//don't change to false even if value is false
			this.setRenderSubmitButton(true);
		}
		
		importedDocumentsModel = new ListDataModel();
		uploadedDocumentsModel =  new ListDataModel();
		
		importedDocumentsModel.setWrappedData(this.getImportedDocumentsList());
		uploadedDocumentsModel.setWrappedData(this.getUploadedDocumentsList());
		
		//documentsModel = new ListDataModel();
		//documentsModel.setWrappedData(this.getDocumentList());

		//@SuppressWarnings("unused")
		//String fromPage = (String) sessionMap.get("from");
		if (fromPage.equalsIgnoreCase("searchPage")) {
			this.setRenderModifyButton(true);
		}
		
		//for imported filings found through searchPage
		if (fromPage.equalsIgnoreCase("searchPage") &&
				caseStatusCode == 2) {
			this.setRenderRejectReasonButton(false);
		}
		

		// set court date
		this.setCourtDate(this.getModelFacade().findCourtDate(
				this.getCaseRecord().getUuid()));
		// set case caption
		if(c.getCaseRecordAction().getId()==3){
			if( !initiatingPartyOrganizationList.isEmpty() && !defendentPartyPersonList.isEmpty() )
			{
				String initiatingPartyOrgName = ((OrgParticipants) initiatingPartyOrganizationList
						.get(0)).getOrganizations().getName();
				Person defendent = ((PersonParticipants) defendentPartyPersonList
						.get(0)).getPerson();
				String defendentName = defendent.getFirstName() + " "
						+ defendent.getMiddleName() + " "
						+ defendent.getLastName();
				String etal = "";
			
				String PcaseCaption = String.format("SCDHS/%s vs %s",etal,defendentName);
				
				this.setCaseCaption(PcaseCaption);
			}
			else{
				//CASE IS INVALID
				this.setCaseCaption("SCDHS/INVALID CASE");
				validCase = false;
			}
			
		}
		else{
		if ( !initiatingPartyOrganizationList.isEmpty() && 	 !initiatingPartyPersonList.isEmpty() &&  !defendentPartyPersonList.isEmpty())
		 {
			String initiatingPartyOrgName = ((OrgParticipants) initiatingPartyOrganizationList
					.get(0)).getOrganizations().getName();
			Person defendent = ((PersonParticipants) defendentPartyPersonList
					.get(0)).getPerson();
			String defendentName = defendent.getFirstName() + " "
					+ defendent.getMiddleName() + " "
					+ defendent.getLastName();
			String etal = "";
			if(initiatingPartyPersonList.size() > 1)
			{
				etal = " et. al.";
			}
			String PcaseCaption = String.format("DHS/%s vs %s",								
					((PersonParticipants)initiatingPartyPersonList.get(0)).getPerson().getFirstName() + " " + 
					((PersonParticipants)initiatingPartyPersonList.get(0)).getPerson().getLastName() + etal,						
					defendentName);
			
			this.setCaseCaption(PcaseCaption);
		}else{
			//CASE IS INVALID
			this.setCaseCaption("DHS/INVALID CASE");
			validCase = false;
		}
	}
		
		if(!allowSendToClerk)
		{
			if(this.renderSubmitButton)
			{
				this.setRenderSubmitButton(false);
			}
		}
		
		if(caseRecord.getStatus().getCode() == Constants.CaseRecordStatus.QUEUED_FOR_IMPORT)
		{
			this.setRenderModifyButton(false);
		}
		
		if(caseRecord.statusEquals(
			Constants.CaseRecordStatus.REJECTED))
		{
			this.setRenderModifyButton(true);
			this.setRenderRejectReasonButton(true);
			this.setRenderSubmitButton(true);
			this.setRenderFileNewDocuments(true);
			this.setRenderSetCourtDate(true);			
			
		}				
			
		
		if(!this.validCase)
		{
			this.setRenderModifyButton(false);
			this.setRenderSubmitButton(false);
		}
		
	}

	public String getSendToCourtText()
	{
		return this.sendToCourtAction.getText(this.courtUuid);
		
	}
	
	/**
	 * This method navigates user to the previous page
	 * 
	 * @return String
	 */
	public String back() {
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		String fromPage = (String) sessionMap.get("from");
		sessionMap.remove("from");
		sessionMap.remove("caseUuid");
		sessionMap.remove("attCaseDetailsPage");

		// sessionMap.put("navigationString", "attFilingsTablesPage");

		if (fromPage.equalsIgnoreCase("allFilingsTablesPage"))
			return "allFilingsPage"; 
		if(fromPage.equalsIgnoreCase("searchPage")) {
			sessionMap.put("from", "attFilingsTablesPage");
			return "searchPage";
		} else
			return "";

	}

	/**
	 * @param initiatingPartyOrganizationDataModel
	 *            The initiatingPartyOrganizationDataModel to set.
	 */
	public void setInitiatingPartyOrganizationDataModel(
			DataModel initiatingPartyOrganizationDataModel) {
		this.initiatingPartyOrganizationDataModel = initiatingPartyOrganizationDataModel;
	}

	/**
	 * @return Returns the caseRecord.
	 */
	public CaseRecord getCaseRecord() {
		return caseRecord;
	}

	/**
	 * Setter for property caseRecord
	 * 
	 * @param caseRecord
	 */
	public void setCaseRecord(CaseRecord caseRecord) {
		this.caseRecord = caseRecord;
	}

	/**
	 * Getter for property filerName
	 * 
	 * @return filerName
	 */
	public String getFilerName() {
		return filerName;
	}

	/**
	 * Setter for property filer
	 * 
	 * @param filerName
	 */
	public void setFilerName(String filerName) {
		this.filerName = filerName;
	}

	/**
	 * Getter for property defendentPartyPersonModel
	 * 
	 * @return defendentPartyPersonModel
	 */
	public DataModel getDefendentPartyPersonModel() {
		return defendentPartyPersonModel;
	}

	/**
	 * Setter for property defendentPartyPersonModel
	 * 
	 * @param defendentPartyPersonModel
	 */
	public void setDefendentPartyPersonModel(DataModel defendentPartyPersonModel) {
		this.defendentPartyPersonModel = defendentPartyPersonModel;
	}

	/**
	 * Getter for property defendentsAttorneyModel
	 * 
	 * @return defendentsAttorneyModel
	 */
	public DataModel getDefendentsAttorneyModel() {
		return defendentsAttorneyModel;
	}

	/**
	 * Setter for property defendentAttorneyModel
	 * 
	 * @param defendentsAttorneyModel
	 */
	public void setDefendentsAttorneyModel(DataModel defendentsAttorneyModel) {
		this.defendentsAttorneyModel = defendentsAttorneyModel;
	}

	/**
	 * Getter for property initaingPartyPersonModel
	 * 
	 * @return initaingPartyPersonModel
	 */
	public DataModel getInitiatingPartyPersonModel() {
		return initiatingPartyPersonModel;
	}

	/**
	 * Setter for property initiatingPartyPersonModel
	 * 
	 * @param initiatingPartyPersonModel
	 */
	public void setInitiatingPartyPersonModel(
			DataModel initiatingPartyPersonModel) {
		this.initiatingPartyPersonModel = initiatingPartyPersonModel;
	}

	/**
	 * Getter for property initatingPartyOrganizationModel
	 * 
	 * @return initiatingPartyOrganizationModel
	 */
	public DataModel getInitiatingPartyOrganizationDataModel() {
		return initiatingPartyOrganizationDataModel;
	}

	/**
	 * Getter for property witnessPersonModel
	 * 
	 * @return witnessPersonModel
	 */
	public DataModel getWitnessPersonModel() {
		return witnessPersonModel;
	}

	/**
	 * Setter for property witnessPersonModel
	 * 
	 * @param witnessPersonModel
	 */
	public void setWitnessPersonModel(DataModel witnessPersonModel) {
		this.witnessPersonModel = witnessPersonModel;
	}

	/**
	 * Getter for property plantiffsAttorneyModel
	 * 
	 * @return plantiffsAttorneyModel
	 */
	public DataModel getPlantiffsAttorneyModel() {
		return plantiffsAttorneyModel;
	}

	/**
	 * Setter for property plantiffsAttorneyModel
	 * 
	 * @param plantiffsAttorneyModel
	 */
	public void setPlantiffsAttorneyModel(DataModel plantiffsAttorneyModel) {
		this.plantiffsAttorneyModel = plantiffsAttorneyModel;
	}

	/*
	 * Getter for property documentsModel
	 * 
	 * @return documentsModel
	 *
	public DataModel getDocumentsModel() {
		return documentsModel;
	}

	/*
	 * Setter for property documentsModel
	 * 
	 * @param documentsModel
	 *
	public void setDocumentsModel(DataModel documentsModel) {
		this.documentsModel = documentsModel;
	}
*/
	/**
	 * Getter for property caseCaption
	 * 
	 * @return caseCaption
	 */
	public String getCaseCaption() {
		return caseCaption;
	}

	/**
	 * Setter for property caseCaption
	 * 
	 * @param caseCaption
	 */
	public void setCaseCaption(String caseCaption) {
		this.caseCaption = caseCaption;
	}

	/**
	 * @return the signatureTrackingID
	 */
	public String getSignatureTrackingID() {
		return signatureTrackingID;
	}

	/**
	 * @param signatureTrackingID
	 *            the signatureTrackingID to set
	 */
	public void setSignatureTrackingID(String signatureTrackingID) {
		this.signatureTrackingID = signatureTrackingID;
	}

	/**
	 * @return the proposedCourtDate
	 */
	public Date getProposedCourtDate() {
		return proposedCourtDate;
	}

	/**
	 * @param proposedCourtDate
	 *            the proposedCourtDate to set
	 */
	public void setProposedCourtDate(Date proposedCourtDate) {
		this.proposedCourtDate = proposedCourtDate;
	}

	/**
	 * @return the importedDocumentsList
	 */
	public List<Documents> getImportedDocumentsList() {
		return importedDocumentsList;
	}

	/**
	 * @param importedDocumentsList the importedDocumentsList to set
	 */
	public void setImportedDocumentsList(List<Documents> importedDocumentsList) {
		this.importedDocumentsList = importedDocumentsList;
	}

	/**
	 * @return the importedDocumentsModel
	 */
	public DataModel getImportedDocumentsModel() {
		reload();
		return importedDocumentsModel;
	}

	/**
	 * @param importedDocumentsModel the importedDocumentsModel to set
	 */
	public void setImportedDocumentsModel(DataModel importedDocumentsModel) {
		this.importedDocumentsModel = importedDocumentsModel;
	}

	/**
	 * @return the uploadedDocumentsList
	 */
	public List<Documents> getUploadedDocumentsList() {		
		return uploadedDocumentsList;
	}

	/**
	 * @param uploadedDocumentsList the uploadedDocumentsList to set
	 */
	public void setUploadedDocumentsList(List<Documents> uploadedDocumentsList) {
		this.uploadedDocumentsList = uploadedDocumentsList;
	}

	/**
	 * @return the uploadedDocumentsModel
	 */
	public DataModel getUploadedDocumentsModel() {
		reload();
		return uploadedDocumentsModel;
	}

	private void reload() {
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String caseUuid = (String) sessionMap.get("caseUuid");
		List<Documents> pdfList = new ArrayList<Documents>();
		List<Documents>iDocs = new ArrayList<Documents>();
		List<Documents>eDocs = new ArrayList<Documents>();
		pdfList = this.getModelFacade().getPDFDocuments(caseUuid);
		//added by Michael A to get the list of pdf's signed  by the attorney or not, to display 
		
		LOG.debug("2 - pdfList.size() is "+pdfList.size());
		for(Documents document : pdfList) {
			int docStatusCode = document.getStatus().getCode();
			if(docStatusCode == Constants.DocumentStatus.IMPORTED) 
			{
				iDocs.add(document);
			} 
			else 
			{
				eDocs.add(document);
			}
		}
		
		this.setDocumentList(pdfList);
		this.setImportedDocumentsList(iDocs);
		this.setUploadedDocumentsList(eDocs);
		if(importedDocumentsModel==null)
		importedDocumentsModel = new ListDataModel();
		if(uploadedDocumentsModel==null)
		uploadedDocumentsModel =  new ListDataModel();
		
		importedDocumentsModel.setWrappedData(this.getImportedDocumentsList());
		uploadedDocumentsModel.setWrappedData(this.getUploadedDocumentsList());
		
	}

	/**
	 * @param uploadedDocumentsModel the uploadedDocumentsModel to set
	 */
	public void setUploadedDocumentsModel(DataModel uploadedDocumentsModel) {
		this.uploadedDocumentsModel = uploadedDocumentsModel;
	}

	/**
	 * This method gets called when user wants to view the PDF/XML Docuement
	 * 
	 * @return String
	 */
	public void viewFile() {
		Documents docUploaded = (Documents) this.getDocumentClicked_Uploaded().getValue();
		Documents docImported = (Documents) this.getDocumentClicked_Imported().getValue();
		Documents docToStream = docUploaded;
		
		if (docToStream == null) { // If the uploaded doc is null, try others
			docToStream = docImported;
		} 
		
		if (docToStream != null) {
			FacesContext context = this.getFacesContext();
			HttpServletResponse resp = (HttpServletResponse) FacesContext
					.getCurrentInstance().getExternalContext().getResponse();
			String docTitle = (String) docToStream.getTitle();
			byte[] docContent = docToStream.getContent();
			try {
				FileUtility.streamReportToBrowser(resp, docTitle, docContent);
			} catch (IOException e) {
				LOG.error("Error in CaseDetailPage.viewFile() method: " + e);
			}
			context.responseComplete();
		} else {
			LOG.debug("Error: Documents Contents Null, not able to be viewed.");
		}
		// TODO Need to add error message informing user of error state		
	}
	
	
	/**
	 * @return the documentClicked_Uploaded
	 */
	public UIParameter getDocumentClicked_Uploaded() {
		return documentClicked_Uploaded;
	}

	/**
	 * @param documentClicked_Uploaded
	 *            the documentClicked_Uploaded to set
	 */
	public void setDocumentClicked_Uploaded(UIParameter documentClicked) {
		this.documentClicked_Uploaded = documentClicked;
	}
	
	/**
	 * @return the documentClicked_Imported
	 */
	public UIParameter getDocumentClicked_Imported() {
		return documentClicked_Imported;
	}

	/**
	 * @param documentClicked_Imported the documentClicked_Imported to set
	 */
	public void setDocumentClicked_Imported(UIParameter documentClicked_Imported) {
		this.documentClicked_Imported = documentClicked_Imported;
	}
	
	/**
	 * Getter for the property documentList
	 * 
	 * @return List<Documents>
	 */
	public List<Documents> getDocumentList() {
		return documentList;
	}

	/**
	 * Setter for the property documentList
	 * 
	 * @param documentList
	 */
	public void setDocumentList(List<Documents> documentList) {
		this.documentList = documentList;
	}

	/**
	 * @return Returns the caseRecordUuid.
	 */
	public String getCaseRecordUuid() {
		return caseRecordUuid;
	}

	/**
	 * @param caseRecordUuid
	 *            The caseRecordUuid to set.
	 */
	public void setCaseRecordUuid(String caseRecordUuid) {
		this.caseRecordUuid = caseRecordUuid;
	}

	/**
	 * @return the renderSignedText
	 */
	public boolean isRenderSignedText() {
		return renderSignedText;
	}

	/**
	 * @param renderSignedText
	 *            the renderSignedText to set
	 */
	public void setRenderSignedText(boolean renderSignedText) {
		this.renderSignedText = renderSignedText;
	}
	
	public boolean isRenderRejectReasonButton() {
		return renderRejectReasonButton;
	}

	public void setRenderRejectReasonButton(boolean renderRejectReasonButton) {
		this.renderRejectReasonButton = renderRejectReasonButton;
	}
	
	public boolean getRenderRejectReasonButton() {
		return this.renderRejectReasonButton;
	}

	/**
	 * @return the organizationName
	 */
	public String getOrganizationName() {
		return organizationName;
	}

	/**
	 * @param organizationName
	 *            sets the organizationName
	 */
	public void setOrganizationName(String organizationName) {
		this.organizationName = organizationName;
	}

	
	public void signDocument(Documents doc) throws Exception {
		Map<String, Object> sessionMap = this.getSessionMap();
		Person personSigner = (Person)sessionMap.get("person");	
		Court c = this.getCaseRecord().getCourt();
		CaseRecord cr = this.getCaseRecord();
		int documentCategory = doc.getDocumentInstance().getDocumentType().getDocumentCategory().getCode();
		if(( documentCategory != 10 && documentCategory != 12))
		{
			/*
			 * Test for Fulton PersonParticipants pt =this.getModelFacade().
			 * getPersonParticipantByParticipantRelationshipCode(cr, 4).get(0);
			 * if(pt.getPerson().getFirstName().equalsIgnoreCase(
			 * "ff20da2c-8e5c-11dd-9b78-0016d3") ||
			 * pt.getPerson().getUuid().equalsIgnoreCase
			 * (personSigner.getUuid())) { pt.setPerson(personSigner); }else{
			 * FacesContext.getCurrentInstance().addMessage(null, new
			 * FacesMessage(FacesMessage.SEVERITY_INFO,
			 * "Case already signed by attorney: " + pt.getPerson().getUserId(),
			 * "Case already signed by attorney: " + pt.getPerson().getUserId()
			 * ));
			 * 
			 * return "stay"; }
			 */
			List<PersonParticipants> pt = this.getModelFacade()
					.getPersonParticipantByParticipantRelationshipCode(cr, 4);
			boolean testSigner = false;
			PersonParticipants personParticipant = null;
			if(c.isAttorneySignatureRestricted()) {
				
				for (int i = 0; i < pt.size(); i++) 
				{
					if (pt.get(i).getPerson().getFirstName().equalsIgnoreCase("ff20da2c-8e5c-11dd-9b78-0016d3")
 					   || pt.get(i).getPerson().getUuid().equalsIgnoreCase(personSigner.getUuid())) 
					{
						pt.get(i).setPerson(personSigner);
						personParticipant = pt.get(i);
						testSigner = true;
						this.getModelFacade().getSession().save(personParticipant);
						break;
					}
				}
			}else{
			    testSigner = true;
			}
			if (!testSigner) {
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_INFO,
								"Case already signed by attorney: ",
								"Case already signed by attorney: "));
				
			}
		}
		
		/*if(c.isVisualSignEnabled()) {
			
			sessionMap.put("documentUuid",((Documents)this.signatureBinding.getValue()).getUuid());
			return "sign";
		}*/
		
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();

		//save original document content in case signature failed
		byte[] originalDocContent = doc.getContent();
		
		byte[] sigInByte = null;
		
		String attorneyRoleUuid = "uuid6"; // The Attorney Role UUID
		
		

		
		// Retrieve the certificate password
		LdapDirectoryPerson ldPerson = this.getModelFacade().findLdapDirectoryByPerson(personSigner);
				
		// Add visual signature first	
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().beginTransaction();
		loadData();
		//pdfStamperController.addVisualSignatureOnDocument(doc,personSigner,ldPerson,attorneyRoleUuid);
		pdfStamperController.addVisualSignatureOnDocument(doc,personSigner,attorneyRoleUuid);
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().beginTransaction();
		loadData();
		// If visual Signature is successfully put on the document then digitally sign
		if(pdfStamperController.isSignedDoc() == true) {
		//	sigInByte = digitalSignerController.signDocument(doc, personSigner,attorneyRoleUuid, ldPerson);
			sigInByte = digitalSignerController.signDocument(doc, personSigner,attorneyRoleUuid);
			// update the signed field in the documents object
			DocumentStatus documentStatus  = new DocumentStatus();
			if(digitalSignerController.isSignedDoc() == true) {
				int statusCode = 11;			//signedByAttorney
				documentStatus = this.getModelFacade().findDocumentStatus(statusCode);
				//for Testing
				//digitalSignerController.updateDatabaseAfterSigned(doc,documentStatus, personSigner, sigInByte);
				this.getModelFacade().updateDocumentStatus(doc.getUuid(), documentStatus);

				
			}
			// update the signed field in the documents object
			doc.setSignedDoc(digitalSignerController.isSignedDoc());
			// for rendering purpose in the xhtml page set the field ordered as false
			doc.setOrderedDoc(digitalSignerController.isOrderedDoc());		
		}
		//Check the status of the doc and if it is 
		//failedAttorneySignature for the clerk then set the corresponding booleans
		//that cause the message to appear on the page indicating the documents
		//with the problem and also for the sign command to reappear
	
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
//	b7006e6c-695c-11dd-945f-00301b45ff56
		if (doc.getContent() == null){	
			doc.setContent(null,originalDocContent);
			CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(personSigner);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(19));
			this.getModelFacade().insertCaseRecordHistory(crh);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		}else if(doc.getStatus().getCode() == 15){
			//Clerk signature failure not necessarily from no contents
			//set the document content with the original content
			doc.setContent(null,originalDocContent);
			CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(personSigner);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(23));
			this.getModelFacade().insertCaseRecordHistory(crh);
			
		}	
		
		boolean docOrder;
		boolean docSigned;
		boolean readyforclerk = true;
		for (Documents docx : this.caseRecord.getDocuments()) {
			docOrder = digitalSignerController.isDocumentOrderForAttorney(docx);
			docSigned = digitalSignerController.isDocumentSignedForAttorney(docx, personSigner);
			if (docOrder) {
				if (!docSigned && !docx.getUuid().equalsIgnoreCase(doc.getUuid())) {
					readyforclerk = false;
				}
			}
		}
		if(readyforclerk)
		{
			this.caseRecord.setStatus(this.getModelFacade().findCaseRecordStatusByCode(11));
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().save(this.caseRecord);
		}

		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		
	}
	
	//TODO: move this method into DocumentSigner bean
	// Frank added the following methods on 3.28.07
	/**
	 * This method is get called when user press the sign button to sign PDF or
	 * XML document
	 * 
	 * @return String
	 * @throws Exception
	 */
	public String signDocument() throws Exception {
		Map<String, Object> sessionMap = this.getSessionMap();
		Person personSigner = (Person)sessionMap.get("person");
		Documents doc = (Documents) this.getSignatureBinding().getValue();
		Court c = this.getCaseRecord().getCourt();
		CaseRecord cr = this.getCaseRecord();
		int documentCategory = doc.getDocumentInstance().getDocumentType().getDocumentCategory().getCode();
		if(( documentCategory != 10 && documentCategory != 12))
		{
			/*
			 * Test for Fulton PersonParticipants pt =this.getModelFacade().
			 * getPersonParticipantByParticipantRelationshipCode(cr, 4).get(0);
			 * if(pt.getPerson().getFirstName().equalsIgnoreCase(
			 * "ff20da2c-8e5c-11dd-9b78-0016d3") ||
			 * pt.getPerson().getUuid().equalsIgnoreCase
			 * (personSigner.getUuid())) { pt.setPerson(personSigner); }else{
			 * FacesContext.getCurrentInstance().addMessage(null, new
			 * FacesMessage(FacesMessage.SEVERITY_INFO,
			 * "Case already signed by attorney: " + pt.getPerson().getUserId(),
			 * "Case already signed by attorney: " + pt.getPerson().getUserId()
			 * ));
			 * 
			 * return "stay"; }
			 */
			List<PersonParticipants> pt = this.getModelFacade()
					.getPersonParticipantByParticipantRelationshipCode(cr, 4);
			boolean testSigner = false;
			PersonParticipants personParticipant = null;
			if(c.isAttorneySignatureRestricted()) {
				
				for (int i = 0; i < pt.size(); i++) 
				{
					if (pt.get(i).getPerson().getFirstName().equalsIgnoreCase("ff20da2c-8e5c-11dd-9b78-0016d3")
 					   || pt.get(i).getPerson().getUuid().equalsIgnoreCase(personSigner.getUuid())) 
					{
						pt.get(i).setPerson(personSigner);
						personParticipant = pt.get(i);
						testSigner = true;
						this.getModelFacade().getSession().save(personParticipant);
						break;
					}
				}
			}else{
			    testSigner = true;
			}
			if (!testSigner) {
				FacesContext.getCurrentInstance().addMessage(
						null,
						new FacesMessage(FacesMessage.SEVERITY_INFO,
								"Case already signed by attorney: ",
								"Case already signed by attorney: "));
				return "stay";
			}
		}
		
		if(c.isVisualSignEnabled()) {
			
			sessionMap.put("documentUuid",((Documents)this.signatureBinding.getValue()).getUuid());
			return "sign";
		}
		
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();

		//save original document content in case signature failed
		byte[] originalDocContent = doc.getContent();
		
		byte[] sigInByte = null;
		
		String attorneyRoleUuid = "uuid6"; // The Attorney Role UUID
		
		

		
		// Retrieve the certificate password
		LdapDirectoryPerson ldPerson = this.getModelFacade().findLdapDirectoryByPerson(personSigner);
				
		// Add visual signature first	
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().beginTransaction();
		loadData();
		//pdfStamperController.addVisualSignatureOnDocument(doc,personSigner,ldPerson,attorneyRoleUuid);
		pdfStamperController.addVisualSignatureOnDocument(doc,personSigner,attorneyRoleUuid);
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().beginTransaction();
		loadData();
		// If visual Signature is successfully put on the document then digitally sign
		if(pdfStamperController.isSignedDoc() == true) {
		//	sigInByte = digitalSignerController.signDocument(doc, personSigner,attorneyRoleUuid, ldPerson);
			sigInByte = digitalSignerController.signDocument(doc, personSigner,attorneyRoleUuid);
			// update the signed field in the documents object
			DocumentStatus documentStatus  = new DocumentStatus();
			if(digitalSignerController.isSignedDoc() == true) {
				int statusCode = 11;			//signedByAttorney
				documentStatus = this.getModelFacade().findDocumentStatus(statusCode);
				//for Testing
				//digitalSignerController.updateDatabaseAfterSigned(doc,documentStatus, personSigner, sigInByte);
				this.getModelFacade().updateDocumentStatus(doc.getUuid(), documentStatus);

				
			}
			// update the signed field in the documents object
			doc.setSignedDoc(digitalSignerController.isSignedDoc());
			// for rendering purpose in the xhtml page set the field ordered as false
			doc.setOrderedDoc(digitalSignerController.isOrderedDoc());		
		}
		//Check the status of the doc and if it is 
		//failedAttorneySignature for the clerk then set the corresponding booleans
		//that cause the message to appear on the page indicating the documents
		//with the problem and also for the sign command to reappear
	
		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
//	b7006e6c-695c-11dd-945f-00301b45ff56
		if (doc.getContent() == null){	
			doc.setContent(null,originalDocContent);
			CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(personSigner);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(19));
			this.getModelFacade().insertCaseRecordHistory(crh);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		}else if(doc.getStatus().getCode() == 15){
			//Clerk signature failure not necessarily from no contents
			//set the document content with the original content
			doc.setContent(null,originalDocContent);
			CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(personSigner);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(23));
			this.getModelFacade().insertCaseRecordHistory(crh);
			
		}	
		
		boolean docOrder;
		boolean docSigned;
		boolean readyforclerk = true;
		for (Documents docx : this.caseRecord.getDocuments()) {
			docOrder = digitalSignerController.isDocumentOrderForAttorney(docx);
			docSigned = digitalSignerController.isDocumentSignedForAttorney(docx, personSigner);
			if (docOrder) {
				if (!docSigned && !docx.getUuid().equalsIgnoreCase(doc.getUuid())) {
					readyforclerk = false;
				}
			}
		}
		if(readyforclerk)
		{
			this.caseRecord.setStatus(this.getModelFacade().findCaseRecordStatusByCode(11));
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().save(this.caseRecord);
		}

		//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		return "stay";		
	}

	public UIParameter getSignatureBinding() {
		return this.signatureBinding;
	}
/*
	private boolean isDocumentSigned(Documents doc, Person person) {
		boolean documentSigned = false;
		boolean ordered = this.isDocumentOrder(doc);

		List<Signatures> docSignatures = new ArrayList<Signatures>();
		docSignatures = doc.getSignatures();
		if ((ordered) && (doc.getStatus().getCode() != 2)) {
			for (Signatures s : docSignatures) {
				Person personSigned = s.getSignedByPerson();
				System.out.println("Signed Person Uuid "
						+ personSigned.getUuid());
				System.out.println("Parameter passes Person Uuid "
						+ person.getUuid());
				if (personSigned.getUuid().equals(person.getUuid())) {
					if (s.getSignatureValue() != null) {
						documentSigned = true;
						doc.setSignedDoc(true);
						doc.setOrderedDoc(false);
					}
				}
				break;
			}
		} else if ((ordered) && (doc.getStatus().getCode() == 2)) {
			documentSigned = true;
			doc.setSignedDoc(true);
		}

		return documentSigned;
	}
*/
	/**
	 * Helper method to check the document is a type of "Order" or "Warrant"
	 * from the given document code
	 * 
	 * @return boolean
	 *//*
	private boolean isDocumentOrder(Documents doc) {

		boolean documentOrder = false;

		// for documents :1)Complaint:Child Support Contempt (129445)
		// 2) Request:Admissions (122920)

		
		 * For document category = "Request","Complaint", "Petition", and
		 * "Motion"
		 

		String docCategory = doc.getDocumentInstance().getDocumentType()
				.getDocumentCategory().getDescription();
		int docInstanceCode = doc.getDocumentInstance().getCode();
		int docTypeCode = doc.getDocumentInstance().getDocumentType().getCode();
		// TODO Will need to change to matching category codes instead of
		// descriptions in future
		// Document Type Code 182 = Notice of Registration
		// Document Type Code 19 = Notice to Produce
		if ((docCategory.equalsIgnoreCase("Request"))
				|| (docCategory.equalsIgnoreCase("Complaint"))
				|| (docCategory.equalsIgnoreCase("Motion"))
				|| (docCategory.equalsIgnoreCase("Petition"))
				|| (docTypeCode == 19)  // Notice to Produce
				|| (docTypeCode == 43) // Notice of Registration
				|| (docTypeCode == 24) // Income Deduction Order
				|| (docTypeCode == 26) // Rule Absolute Order
				|| (docTypeCode == 23) // Final Order
				|| (docTypeCode == 28) // Support Order
				|| (docTypeCode == 22)) {  // Contempt Order
			documentOrder = true;
			doc.setOrderedDoc(true);
		} else {
			documentOrder = false;
			doc.setOrderedDoc(false);
		}
		
		 * if((docCode.equals("129445"))||(docCode.equals("122920"))){
		 * System.out.print("The document code is " + docCode); LOG.info("The
		 * document code is " + docCode); documentOrder = true;
		 * doc.setOrderedDoc(true); } else { documentOrder = false;
		 * doc.setOrderedDoc(false); }
		 
		return documentOrder;
	}*/

	/**
	 * This method signs the PDF documents. After signing updates the mySQL
	 * database. Then sends the documents signed to Judge and then email
	 * notification to OCSS that documents are signed and sent to Clerk.
	 * 
	 * @param doc
	 * @throws Exception
	 */
	private void signPDFDocument(Documents doc) throws Exception {

		DateFormat format = new SimpleDateFormat("MM/dd/yyyy");

		byte[] docContent = doc.getContent();
		ByteArrayInputStream document = new ByteArrayInputStream(docContent);
		LOG.info("Entering Digital Signer...");
		DigitalSigner pdfSigner = new DigitalSigner();
		Person personSigned = (Person) this.getFacesContext()
				.getExternalContext().getSessionMap().get("person");
		// Blocked this line to test LdapDirectoryPerson table
		// personSigned.setCnName("Sample Person");
		LdapDirectoryPerson ldPerson = this.getModelFacade()
				.findLdapDirectoryByPerson(personSigned);
		String cnName = ldPerson.getCname();
		String password = ldPerson.getCertPassword();
		/*
		 * String personCN =
		 * (this.getModelFacade().findPersonById(personSigned.getUuid())).getCnName();
		 */
		// byte[] sigInByte =pdfSigner.sign(document, personSigned.getCnName());
		String doctype = new Integer(doc.getDocumentInstance().getCode())
				.toString();
		LOG.info("The docType is .." + stripOfAllNonAlphaNumeric(doctype));
		// this.signatureCounter = (Counter)this.getModelFacade().getCounter();
		// added the following line on 4/4/07 to distinguish this to Judge model
		// doc.setVersion(1);
		// added the following
		LdapClient ldapClient = new LdapClient();
		Image image = ldapClient.retrieveSignatureImage(cnName);
		PDFStamper pdfStamper = new PDFStamper();
		// TODO Improve the creation of the target based on the person
		//String targetForSignature = new String("~" + cnName.toCharArray()[0]);
		// TODO Does this signing process work for all counties?
		/*
		 * TODO The signature target needs to be pulled from DB as a 
		 * configuration option for each signer.
		 */ 
		String targetForSignature = new String("~" + cnName);
		// Temp work around for Notice to Produce in Bibb County
		String altTargetForSignature = new String (cnName);
		//String altTargetForSignature2 = new String ("Sherita Strange Peeler");
		byte[] tempDocContents = pdfStamper.addVisualSignatureIndicator(
				doc, 
				image, 
				personSigned, 
				targetForSignature);
		if (tempDocContents == null){
			tempDocContents = pdfStamper.addVisualSignatureIndicator(
					doc, 
					image, 
					personSigned, 
					altTargetForSignature);
		}
		/*
		if (tempDocContents == null){
			tempDocContents = pdfStamper.addVisualSignatureIndicator(
					doc, 
					image, 
					personSigned, 
					altTargetForSignature2);
		}*/
		if (tempDocContents == null) {
			LOG.info("Error applying visual signature indicator image . . .");
			LOG.error("Error applying visual signature indicator image for" + cnName);
			
			return;
		}
		doc.setContent(null,tempDocContents);

		byte[] sigInByte = pdfSigner.sign(document, cnName, password);

		LOG.info("Document signed!!...");
		// set the document status as signed in DocumentType Table.
		// this.getModelFacade().updateDocumentStatus(docUuid,6);
		GregorianCalendar expirationDate = new GregorianCalendar(2016, 8, 18,
				19, 24, 8);
	
		GregorianCalendar currentDate = new GregorianCalendar();
		currentDate.setTime(DateUtil.getCurrentDate());
		String dateString = currentDate.getTime().toString();
		LOG.debug("The current date for signature is: " + dateString);
		// update the signed field in the documents object
		doc.setSignedDoc(true);
		// for rendering purpose in the xhtml page set the field ordered as
		// false
		doc.setOrderedDoc(false);

		UUID uuid = UUID.randomUUID();
		// LOG.info("Checking if signer is in the counterPerSigner table!!...");
		boolean isSigner = this.getModelFacade().isSigner(
				personSigned.getUuid());
		// LOG.info("The result of the isSigner is ..."+isSigner);
		// check if the signer is in the table counterPerSigner
		if (!isSigner) {
			LOG
					.info("the signer is not in the counterPerSigner table so we put the signer in the table!!...");
			CounterPerSigner counterForThisSigner = new CounterPerSigner();
			counterForThisSigner.setCounterUuid(uuid.toString());
			counterForThisSigner.setCounterValue(1);
			counterForThisSigner.setDateOfLastSignature(DateUtil.getCurrentDate());
			counterForThisSigner.setPersonUuid(personSigned.getUuid());
			this.getModelFacade().insertCounterPerSigner(counterForThisSigner);
		}
		LOG.info("Get the persisted state of the object counterPerSigner for "
				+ personSigned.getUuid()
				+ "  ! and copy it to signatureCounterPerSigner");
		signatureCounterPerSigner = this.getModelFacade()
				.findCounterPerSignerBySignerUuid(personSigned.getUuid());
		
		//LdapDirectoryPerson ldapSigner = this.getModelFacade().findLdapDirectoryByPerson(personSigned);
		//String ldapUserId = ldapSigner.getUid();
		String ldapUserId = ldPerson.getUid();
		String sigPerSignerTrackingId = format.format(DateUtil.getCurrentDate()).toString()
				+ " "
				+ ldapUserId
				+ " "
				+ new Integer(this.signatureCounterPerSigner.getCounterValue())
						.toString(); 
		
		//log.debug(sigPerSignerTrackingId + "   SignatureTrackingID");
	
		
		// sigPerSignerTrackingId = new Date().toString()+"
		// "+personSigned.getCnName()+" "+new
		// Integer(this.signatureCounterPerSigner.getCounterValue()).toString();
		// this.setSignatureTrackingID(format.format(new Date()).toString()+ "
		// "+personSigned.getCnName()+" "+new
		// Integer(this.signatureCounterPerSigner.getCounterValue()).toString());
		this.setSignatureTrackingID(stripOfAllSlashes(
				format.format(DateUtil.getCurrentDate()).toString())
				+ personSigned.getUserId()
				+ new Integer(this.signatureCounterPerSigner.getCounterValue())
						.toString() 
				+ stripOfAllNonAlphaNumeric(doctype));
		this.getModelFacade().updateCounterPerSigner(personSigned.getUuid());

		// Insert the signature value and the corresponding fields in the
		// Signature Table.
		LOG.info("Creating a signatures object and persisting it...");
		Signatures sig = new Signatures();
		sig.setSignatureValue(sigInByte);
		sig.setCertificateChain(SignatureAndCertChain.certificationChain);
		sig.setCreationDate(DateUtil.GregorianCalendarToSqlDate(currentDate));
		sig.setExpirationDate(DateUtil
				.GregorianCalendarToSqlDate(expirationDate));
		sig.setSignedByPerson(personSigned);
		sig.setDocument(doc);
		X509Certificate x509Certificate = this
				.getX509Certificate(SignatureAndCertChain.certificationChain);
		sig.setX509Certificate(x509Certificate);
		sig.setIssuerName(x509Certificate.getIssuerDN().getName());
		sig.setIssuerNumber(x509Certificate.getSerialNumber());
		sig.setDigestValue(null);
		sig.setSignatureTrackingId(this.getSignatureTrackingID());

		this.getModelFacade().makePersistent(sig);

		// commit the transaction
		//HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//		.getTransaction().commit();

		this.renderSignedText = true;
		this.renderSignButton = false;
		
		// Validate the Signature
		SignatureValidator sigVal = new SignatureValidator();
		// sigVal.validate(docContent,SignatureAndCertChain.signature,SignatureAndCertChain.certificationChain);
		sigVal.validate(docContent, sigInByte,
				SignatureAndCertChain.certificationChain);

		this.verifyCertForExpirationDate(x509Certificate, DateUtil.getCurrentDate());
		LOG.info("Expiration Date of certificate is verified");
		LOG.error("Expiration Date of certificate is verified");

		/*
		 * Change all this after Attorney finishes signing on all documents.
		 * 
		 * //Change the Status in the MySQl Database as "ReadyToSendToCourt"
		 * 
		 * this.getModelFacade().updateCaseRecordStatus(this.getCaseRecordUuid(),new
		 * CaseRecordStatus(11,"ReadyToSendToCourt")); //remove the Modify
		 * Button from the Page this.setRenderModifyButton(false); //Put the
		 * Submit Button on the Page to Submit the Filing to Court
		 * this.setRenderSubmitButton(true);
		 */
	}

	private X509Certificate getX509Certificate(byte[] certificationChain)
			throws IOException, CertificateException {

		X509Certificate cert = null;
		SignatureValidator validator = new SignatureValidator();
		InputStream in = new ByteArrayInputStream(certificationChain);

		// read the certificate file and save it into the string
		String certChainBase64Encoded = null;
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		certChainBase64Encoded = br.readLine();

		CertPath certPath = validator
				.loadCertPathFromBase64String(certChainBase64Encoded);
		List certsInChain = certPath.getCertificates();
		X509Certificate[] X509CertificateChain = (X509Certificate[]) certsInChain
				.toArray(new X509Certificate[0]);
		cert = X509CertificateChain[0];

		// System.out.println("Subject Name "+cert.getSubjectDN().getName());
		// System.out.println("Issuer's Distinguish Name
		// "+cert.getIssuerX500Principal().getName());

		return cert;
	}

	private void verifyCertForExpirationDate(X509Certificate cert, Date date)
			throws CertificateExpiredException,
			CertificateNotYetValidException, CertificateParsingException {

		String name2 = cert.getIssuerDN().getName();
		System.out.println("Issuer DN :" + name2);
		String name = cert.getSubjectDN().getName();
		System.out.println("Subject DN : " + name);

		String name3 = cert.getIssuerX500Principal().getName();
		System.out.println("Issuer Principal :" + name3);
		System.out.println("Serial Number :" + cert.getSerialNumber());
		cert.checkValidity(date);
	}

	private void sendEmailNotification(Documents doc, String nameOfPerson)
			throws Exception {

		/**
		 * 3. send notification to the OCSS that documents are signed and sent
		 * to the clerk.
		 */
		// put the ocss e-mail id
		DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
		String email = "tapshals@gaaoc.us";
		String subject = "Document Filed To Court Notification";
		String message = "The File " + doc.getTitle() + " is Signed by "
				+ nameOfPerson + " " + "on date " + format.format(DateUtil.getCurrentDate())
				+ ".";

		//EmailController emailController = new EmailController();
		//emailController.send(email, "admin@gaaoc.us", subject, message);
	}

	public static byte[] getBytesFromFile(InputStream is) throws IOException {
		// InputStream is = new FileInputStream(file);

		// Get the size of the file
		// long length = file.length();
		long length = is.available();

		// You cannot create an array using a long type.
		// It needs to be an int type.
		// Before converting to an int type, check
		// to ensure that file is not larger than Integer.MAX_VALUE.
		if (length > Integer.MAX_VALUE) {
			// File is too large
		}

		// Create the byte array to hold the data
		byte[] bytes = new byte[(int) length];

		// Read in the bytes
		int offset = 0;
		int numRead = 0;
		while (offset < bytes.length
				&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
			offset += numRead;
		}

		// Ensure all the bytes have been read in
		if (offset < bytes.length) {
			// throw new IOException("Could not completely read file
			// "+file.getName());
			throw new IOException("Could not completely read file ");
		}

		// Close the input stream and return bytes
		is.close();
		return bytes;
	}

	public void setSignatureBinding(UIParameter signatureBinding) {
		this.signatureBinding = signatureBinding;
	}

	/**
	 * This method navigates user to display the details of Signature on the
	 * next page
	 * 
	 * @return
	 * @throws Exception
	 * 
	 * Writer: Michael A.
	 */
	public String viewSignatureDetails() throws Exception {
		return "viewSignatureDetails";
	}

	/**
	 * @return Returns the signatures list.
	 */
	public DataModel getSignaturesListModel() {
		return signaturesListModel;
	}

	/**
	 * @param sets
	 *            the signatures list.
	 */
	public void setSignaturesListModel(DataModel signaturesListModel) {
		this.signaturesListModel = signaturesListModel;
	}

	/**
	 * @return the signaturesList
	 */
	public List<Signatures> getSignaturesList() {
		return signaturesList;
	}

	/**
	 * @param sets
	 *            signaturesList
	 */
	public void setSignaturesList(List<Signatures> signaturesList) {
		this.signaturesList = signaturesList;
	}

	/**
	 * @return Returns the sigantureCounterPerSignerModel.
	 */
	public DataModel getSigantureCounterPerSignerModel() {
		return sigantureCounterPerSignerModel;
	}

	/**
	 * @param sets
	 *            the sigantureCounterPerSignerModel.
	 */
	public void setSigantureCounterPerSignerModel(
			DataModel sigantureCounterPerSignerModel) {
		this.sigantureCounterPerSignerModel = sigantureCounterPerSignerModel;
	}

	/**
	 * @return Returns the signatureCounterModel.
	 */
	public DataModel getSignatureCounterModel() {
		return signatureCounterModel;
	}

	/**
	 * @param sets
	 *            the signatureCounterModel.
	 */
	public void setSignatureCounterModel(DataModel signatureCounterModel) {
		this.signatureCounterModel = signatureCounterModel;
	}

	/**
	 * @return Returns a docSignedByThisPerson
	 */
	public Documents getDocSignedByThisPerson() {
		return docSignedByThisPerson;
	}

	/**
	 * @param sets
	 *            a docSignedByThisPerson.
	 */
	public void setDocSignedByThisPerson(Documents docSignedByThisPerson) {
		this.docSignedByThisPerson = docSignedByThisPerson;
	}

	/*
	 * @return Returns the signatureCounter.
	 */
	public Counter getSignatureCounter() {
		return signatureCounter;
	}

	/**
	 * @param sets
	 *            the signatureCounter.
	 */
	public void setSignatureCounter(Counter signatureCounter) {
		this.signatureCounter = signatureCounter;
	}

	/*
	 * public Documents getSignedDoc() { return signedDoc; }
	 * 
	 * public void setSignedDoc(Documents signedDoc) { this.signedDoc =
	 * signedDoc; }
	 */
	public String getSignatureConfTrackNumber() {
		return signatureConfTrackNumber;
	}

	public void setSignatureConfTrackNumber(String signatureConfTrackNumber) {
		this.signatureConfTrackNumber = signatureConfTrackNumber;
	}

	public CounterPerSigner getSignatureCounterPerSigner() {
		return signatureCounterPerSigner;
	}

	public void setSignatureCounterPerSigner(
			CounterPerSigner signatureCounterPerSigner) {
		this.signatureCounterPerSigner = signatureCounterPerSigner;
	}

	/**
	 * @return the courtDate
	 */
	public Date getCourtDate() {
		return courtDate;
	}

	/**
	 * @param courtDate
	 *            the courtDate to set
	 */
	public void setCourtDate(Date courtDate) {
		this.courtDate = courtDate;
	}

	/**
	 * @return the renderModifyButton
	 */
	public boolean isRenderModifyButton() {
		return renderModifyButton;
	}

	/**
	 * @param renderModifyButton
	 *            the renderModifyButton to set
	 */
	public void setRenderModifyButton(boolean renderModifyButton) {
		this.renderModifyButton = renderModifyButton;
	}

	/**
	 * @return the renderSubmitButton
	 */
	public boolean isRenderSubmitButton() {
		return renderSubmitButton;
	}

	/**
	 * @param renderSubmitButton
	 *            the renderSubmitButton to set
	 */
	public void setRenderSubmitButton(boolean renderSubmitButton) {
		this.renderSubmitButton = renderSubmitButton;
	}

	/**
	 * @return the renderSignButton
	 */
	public boolean isRenderSignButton() {
		return renderSignButton;
	}

	/**
	 * @param renderSignButton
	 *            the renderSignButton to set
	 */
	public void setRenderSignButton(boolean renderSignButton) {
		this.renderSignButton = renderSignButton;
	}

	/**
	 * @return the jurisdiction
	 */
	public String getJurisdiction() {
		return jurisdiction;
	}

	/**
	 * @param jurisdiction the jurisdiction to set
	 */
	public void setJurisdiction(String jurisdiction) {
		this.jurisdiction = jurisdiction;
	}

	public void sendToCourt(String crUuid) {
	    //HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//.getTransaction().begin();
	    
	    String  comments=(String) getCommentsInput().getSubmittedValue();
	    
		Person person = (Person)this.getFacesContext().getExternalContext().getSessionMap().get("person");
		courtUuid = (String)this.getFacesContext().getExternalContext().getSessionMap().get("courtUuid");
	  
	    sendToCourtAction.sendToCourt(crUuid, person, this.getModelFacade(),this.courtUuid,comments);
	    
		this.setRenderSubmitButton(false);

		//HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//		.getTransaction().commit();
		
		this.getFacesContext().getExternalContext().getSessionMap().remove("caseRecord");
		this.getFacesContext().getExternalContext().getSessionMap().remove("attCaseDatailsPage");
		
	}
	
	/*
	 * method to file new documents to existing case
	 */
	
	public String fileNewDocuments() {
	   // HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//.getTransaction().begin();
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		sessionMap.put("caseRecord", this.getCaseRecord());
		Person person = (Person) this.getFacesContext()
		.getExternalContext().getSessionMap().get("person");
		String crUuid = (String) sessionMap.get("caseUuid");
		CaseRecordStatus crs = this.getModelFacade().findCaseRecordStatusByCode(15);
		this.getModelFacade().updateCaseRecordStatus(crUuid, crs, courtUuid);
		this.getModelFacade().addCaseRecordHistory(crUuid, 13, person, courtUuid,getComments());  //Filing Readied For Addition
		// commit the transaction
		//HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//.getTransaction().commit();
		sessionMap.put("externalCaseCategoryCode",this.getCaseRecord().getCaseRecordAction().getId());
		String toString = "fileNewDocuments";
		return toString;
	}

	private void sendEmailNotification(String emailToAgent, String emailToCourt) throws Exception {
		DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
		// GregorianCalendar calendar = new GregorianCalendar();
		// put Attorney's e-mail id
		//String emailToAgent = "mcelratr@gaaoc.us";
		//String emailToCourt = "tapshals@gaaoc.us";
		String subject = "Filing Notification";
		String message = "The File is ready to review on date "
				+ format.format(DateUtil.getCurrentDate()) + ".";

		//EmailController emailController = new EmailController();
		 //emailController.send(emailToAgent, "OCSS_Attorney@gaaoc.us", subject,
		// message);
		// emailController.send(emailToCourt, "OCSS_Attorney@gaaoc.us", subject,
		// message);
	}

	public String modifyFiling() {
		String navigationString = "";
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		sessionMap.put("caseRecord", this.getCaseRecord());
		sessionMap.put("from", "attorneyCaseDetailsPage");
		Person person = (Person) this.getFacesContext().getExternalContext().getSessionMap().get("person");
		String crUuid = (String) sessionMap.get("caseUuid");
		CaseRecordStatus crs = this.getModelFacade().findCaseRecordStatusByCode(16);	//sentToAttorneyAddition
		this.getModelFacade().updateCaseRecordStatus(crUuid, crs, courtUuid);
		this.getModelFacade().addCaseRecordHistory(crUuid, 13, person, courtUuid,getComments());  //Filing Readied For Addition
		sessionMap.put("externalCaseCategoryCode",this.getCaseRecord().getCaseRecordAction().getId());
		navigationString = "modify";
		return navigationString;
	}

	public String rejectFiling() {
		String navigationString = "";
		Map sessionMap = this.getFacesContext().getExternalContext()
				.getSessionMap();
		sessionMap.put("caseRecord", this.getCaseRecord());
		navigationString = "reject";
		return navigationString;
	}

	/*
	 * Change the status to something else so that only Judge can see that.
	 */
	public String sendToJudge() {
		this.getModelFacade().updateCaseRecordStatus(this.getCaseRecordUuid(),
				new CaseRecordStatus(13, "ReceivedByJudge"), courtUuid);
		Person person = (Person)this.getFacesContext().getExternalContext().getSessionMap().get("person");
		this.getModelFacade()
				.addCaseRecordHistory(this.getCaseRecordUuid(), 11, person, courtUuid,getComments());
		this.setRenderSubmitButton(false);
		// commit the transaction
		//HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//		.getTransaction().commit();
		String emailToAgent = "mcelratr@gaaoc.us";
		String emailToJudge = "tapshals@gaaoc.us";
		try {
			this.sendEmailNotification(emailToAgent,emailToJudge);
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.getFacesContext().getExternalContext().getSessionMap().remove(
				"caseRecord");
		this.getFacesContext().getExternalContext().getSessionMap().remove(
				"attCaseDatailsPage");

		return "allFilingsPage";
	}

	public String submitCourtDate() {
		

		// this.getModelFacade().updateCourtDate(this.getCaseRecord().getUuid(),this.getProposedCourtDate());
		//Start the transaction
		//HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//	.getTransaction().begin();
		
		
		Person personLoggingIn = (Person) this.getFacesContext()
			.getExternalContext().getSessionMap().get("person");
		String updatePersonUuid = personLoggingIn.getUuid();
		
		this.getModelFacade().updateCourtDate(this.getCaseRecord().getUuid(),
				this.getProposedCourtDate(), updatePersonUuid);
		//Frank added the following block to track the caseRecord
		
		CaseRecordHistory crh = new CaseRecordHistory();
		crh.setCaseRecord(caseRecord);
		// Set event to "Attorney Set Court Date" (21)
		crh.setEventType(this.getModelFacade().findCaseRecordEventType(21));
		crh.setEventDateTime(DateUtil.getCurrentDate());
		crh.setPerson(personLoggingIn);
		this.getModelFacade().insertCaseRecordHistory(crh);
		
	//End
		
		// this.getModelFacade().updateCourtHearingNegotiationStausToRejected(this.getCourtHearingNegotiations());
		
		//Added by Frank to put court date onto Rule NISI
			for (Documents doc : documentList) {
				int docTypeCode = doc.getDocumentInstance().getDocumentType()
					.getCode();
				int docStatusCode = doc.getStatus().getCode();
				byte[] originalContent = doc.getContent();
				if ((docTypeCode == 27) && (docStatusCode == 1 || 
						docStatusCode == 4 || docStatusCode == 6)  ) {
					
					PDFStamper pdfStamper = new PDFStamper();
					String targetForAttorneySignedDate = "+";
					byte[] newContent = pdfStamper.addDate(doc, this.getProposedCourtDate(),
							targetForAttorneySignedDate);
					//this.getModelFacade().makePersistenet(doc);
					if (newContent != null) {
					    doc.setContent(null,newContent);
					} else {
					    doc.setContent(null,originalContent);
					    LOG.debug("Court Date target not " +
					    		"found in document. " +
					    		"Contents Unchanged.");
					}
				}
			}
		//End	
			
		// commit the transaction
		///	HibernatePhaseListener.getSessionFactory().getCurrentSession()
		//	.getTransaction().commit();

		return "stay";
	}

	public void validateDate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException, Exception {
		java.util.Date newValue = (java.util.Date) value;

		/*
		 * There is a bug in jsf page to pass over a date value, the passed
		 * value is always 1 day behind . The day field of the Calendar object
		 * starts with 1 but the month field starts with 0. This confusion might
		 * be the cause of the bug.
		 */
		if (!isValidDate(newValue)) {
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
		Calendar c = new GregorianCalendar();
		c.setTime(newValue);

		System.out.println("Month = " + c.get(Calendar.MONTH));
		System.out.println("Date = " + c.get(Calendar.DATE));

		int date = c.get(Calendar.DATE);
		c.set(Calendar.DATE, date + 1);
		newValue = c.getTime();

		
	}

	/**
	 * Utiltiy method to validate date.
	 * 
	 * true if the new entered date is either equal to current date or a future
	 * date.
	 * 
	 * @param value
	 *            Date
	 * @return boolean
	 */
	protected boolean isValidDate(java.util.Date value) throws Exception {
		boolean validField = false;
		if ((value.compareTo(DateUtil.getCurrentDate()) <= 0) ) {
			validField = false;
			message = Messages.getMessage(
					"us.gaaoc.framework.webapp.util.errorMessage",
					"incorrectDate", null);
			message.setDetail(message.getDetail());
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
		} else {
			Calendar cal = new GregorianCalendar();
			cal.setTime(value);
			int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
			if(dayOfWeek == 1 || dayOfWeek == 7) {
				validField = false;
				message = Messages.getMessage(
						"us.gaaoc.framework.webapp.util.errorMessage",
						"incorrectDate", null);
				message.setDetail(message.getDetail());
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
			}else {
				validField = true;
			}
		}
		return validField;
	}

	private boolean isAllDocumentsSigned(List<Documents> docs, Person person) {
		boolean documentsSigned = false;
		boolean ordered = false;
		List<Documents> orderedDocs = new ArrayList<Documents>();
		for (Documents d : docs) {
			ordered = digitalSignerController.isDocumentOrderForAttorney(d);			
			if (ordered) {
				orderedDocs.add(d);
			}
		}
		List<Signatures> docSignatures = new ArrayList<Signatures>();
		if(! orderedDocs.isEmpty()) {
			for (Documents oDoc : orderedDocs) {
				docSignatures = oDoc.getSignatures();
				documentsSigned = false;
				for (Signatures s : docSignatures) {
					Person personSigned = s.getSignedByPerson();
					System.out.println("Signed Person Uuid "
							+ personSigned.getUuid());
					System.out.println("Parameter passes Person Uuid "
							+ person.getUuid());
					if (personSigned.getUuid().equals(person.getUuid())) {
						documentsSigned = true;
						break;
					}
					//break;
				}
				if (!documentsSigned) 
					break;		
			}
		}else {
			documentsSigned = true;
		}
		return documentsSigned;
	}

	private void updateDatabaseAfterAllSigned(List<Documents> docs,
			Person person) {
		CaseRecord caseRecord = this.getCaseRecord();
		/* Codes:
		 * 
		 * CaseRecordStatus 3: Rejected(By Clerk)
		 * CaseRecordStatus 10: SentToAttorney
		 * CaseRecordStatus 16: SentToAttorneyAddition
		 * CaseRecordStatus 11: ReadyToSendToCourt
		 */
		int caseStatusCode = caseRecord.getStatus().getCode();
		boolean allDocsSigned = this.isAllDocumentsSigned(docs, person);
		if (allDocsSigned
				&& ((caseStatusCode == 10)
						|| (caseStatusCode ==16 ))
				) {
		 	this.getModelFacade().updateCaseRecordStatus(
				this.getCaseRecordUuid(),
				new CaseRecordStatus(11, "ReadyToSendToCourt"), courtUuid);
		 	
		 	//Frank added the following block to track the caseRecord
		    CaseRecordHistory crh = new CaseRecordHistory();
			crh.setCaseRecord(caseRecord);
			crh.setEventDateTime(DateUtil.getCurrentDate());
			crh.setPerson(person);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().begin();
			crh.setEventType(this.getModelFacade().findCaseRecordEventType(10));
			this.getModelFacade().insertCaseRecordHistory(crh);
			//HibernatePhaseListener.getSessionFactory().getCurrentSession().getTransaction().commit();
		//End
			
			this.setRenderSubmitButton(true);
			this.setRenderModifyButton(false);
		} else if (allDocsSigned && caseStatusCode == 3) {  
			this.setRenderSubmitButton(true); 
			this.setRenderModifyButton(true); 
		} else if (allDocsSigned && caseStatusCode  == 11) {
			this.setRenderSubmitButton(true);
			this.setRenderModifyButton(true);
		}
	}

	//Added by Frank
	private boolean isAllDocumentsImported(List<Documents> docs) {
		boolean allDocumentImported = false;
		for (Documents doc : docs) {
			if (doc.getStatus().getCode() != 2) {
				allDocumentImported = false;
				break;
			} else {
				allDocumentImported = true;
			}
		}
		return allDocumentImported;
	}
	//End
	
	private String stripOfAllSlashes(String string) {
		String slash = "/";
		if (string.indexOf(slash) != -1) {
			string = string.substring(0, string.indexOf(slash))
					+ string.substring(string.indexOf(slash) + 1);
			if (string.indexOf(slash) != -1) {
				string = string.substring(0, string.indexOf(slash))
						+ string.substring(string.indexOf(slash) + 1);
				return string;
			} else {
				return string;
			}
		} else {
			return string;
		}
	}

	private String stripOfAllNonAlphaNumeric(String string) {
		String space = " ";
		char spChar = space.charAt(0);
		char colonChar = ":".charAt(0);
		char singleQ = "\'".charAt(0);
		string = removeChar(string, spChar);
		string = removeChar(string, colonChar);
		string = removeChar(string, singleQ);

		return string;
	}

	private String removeChar(String s, char c) {
		String r = "";
		for (int i = 0; i < s.length(); i++) {
			if (s.charAt(i) != c)
				r += s.charAt(i);
		}
		return r;
	}

	public String getOCSSCaseNumber() {
		return OCSSCaseNumber;
	}

	public void setOCSSCaseNumber(String caseNumber) {
		OCSSCaseNumber = caseNumber;
	}

	public String getCourtCaseNumber() {
		return courtCaseNumber;
	}

	public void setCourtCaseNumber(String courtCaseNumber) {
		this.courtCaseNumber = courtCaseNumber;
	}

	public boolean isRenderFileNewDocuments() {
		return renderFileNewDocuments;
	}

	public void setRenderFileNewDocuments(boolean renderFileNewDocuments) {
		this.renderFileNewDocuments = renderFileNewDocuments;
	}
	
	public void onCaseUuidChange(String caseUuid){
		Map sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();	 	
	 	sessionMap.put("caseUuid", caseUuid);
	 	sessionMap.put("from", "trashcanPage");	 
	 	this.loadData();
	 }
	/*public boolean isRenderUpdateCourtCaseNumber() {
		return renderUpdateCourtCaseNumber;
	}

	public void setRenderUpdateCourtCaseNumber(boolean renderUpdateCourtCaseNumber) {
		this.renderUpdateCourtCaseNumber = renderUpdateCourtCaseNumber;
	}
	
	public void updateCourtCaseNumber(){
		Map sessionMap = this.getFacesContext().getExternalContext().getSessionMap();
		String crUuid = (String) sessionMap.get("caseUuid");
		CaseRecord c = this.getModelFacade().findCaseRecordById(crUuid,courtUuid);
			this.getModelFacade().updateCaseRecordCourtTrackingID(crUuid, this.courtCaseNumber, courtUuid);
	}
	*/
}
